package cn.zt.service.impl;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.zt.domain.dao.User;
import cn.zt.domain.dto.LoginFormDTO;
import cn.zt.domain.dto.UserDTO;
import cn.zt.domain.pojo.Result;
import cn.zt.domain.vo.UserVO;
import cn.zt.mapper.UserMapper;
import cn.zt.service.IUserService;
import cn.zt.utils.UserHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Objects;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验账号
        String account = loginForm.getAccount();
        if (account == null){
            return Result.fail("账号不能为空！");
        }
        boolean accountInvalid = (account.length() >= 2 && account.length() <= 16);
        if (!accountInvalid){
            return Result.fail("账号格式错误！");
        }
        //校验密码
        String code = loginForm.getPassword();
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));

        if (ObjectUtil.isEmpty(user)) {
            return Result.fail("用户不存在");
        }

        if (!Objects.equals(user.getPassword(), code)) {
            return Result.fail("密码信息错误");
        }

        //生成token
        String token = UUID.randomUUID().toString(true);

        user.setToken(token);
        userMapper.updateById(user);

        UserVO userVO = new UserVO(user.getId(), user.getName(), token, user.getClazz());
        UserHolder.saveUser(new UserDTO(userVO.getId(), userVO.getName(),loginForm.getAccount(), loginForm.getPassword(), userVO.getToken(), userVO.getClazz()));
        return Result.ok(userVO);
    }

}
